"use strict";

module.exports = (app) => {
  const { STRING, INTEGER, BOOLEAN, DATE, TEXT } = app.Sequelize;

  const Category = app.model.define("category", {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    parent_id: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "父分类ID，0表示顶级分类",
    },
    level: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 1,
      comment: "分类层级",
    },
    name: {
      type: STRING(50),
      allowNull: false,
      comment: "分类名称",
    },
    icon: {
      type: STRING(255),
      comment: "分类图标",
    },
    image: {
      type: STRING(255),
      comment: "分类图片",
    },
    sort_order: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: "排序",
    },
    is_show: {
      type: BOOLEAN,
      allowNull: false,
      defaultValue: true,
      comment: "是否显示",
    },
    created_at: DATE,
    updated_at: DATE,
  });

  // 关联关系
  Category.associate = function () {
    // 分类与商品：一对多关系
    app.model.Category.hasMany(app.model.Product, {
      foreignKey: "category_id",
    });

    // 分类的自关联：一个分类有多个子分类
    app.model.Category.hasMany(app.model.Category, {
      foreignKey: "parent_id",
      as: "children",
    });
    app.model.Category.belongsTo(app.model.Category, {
      foreignKey: "parent_id",
      as: "parent",
    });
  };

  return Category;
};
